package bTree.LeetCode;

import java.util.LinkedList;
import java.util.Queue;

public class 路径总和3 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int res = 0;

    public int pathSum(TreeNode root, int targetSum) {
        if (null==root)return res;
        //思路就是广度优先搜索枚举每个节点作为起点，然后以该起点深度优先搜索记录路径值，看符合条件的
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (null!=node.left){
                    queue.add(node.left);
                }
                if (null!=node.right){
                    queue.add(node.right);
                }
                dfs(node,0L,targetSum);
            }
        }
        return res;
    }

    private void dfs(TreeNode node, long path,int targetSum) {
        if (null==node){
            return;
        }
        path+=node.val;
        if (path==targetSum){
            res++;
        }
        dfs(node.left,path,targetSum);
        dfs(node.right,path,targetSum);
    }
}